package com.lanp.springmongodb.config.mongo;

import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoClientFactory;
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import java.util.stream.Collectors;

/**
 * 最后将 MongoTemplate 信息注入到对应的包路径下：
 **/
@Configuration
@EnableMongoRepositories(basePackages = "com.lanp.springmongodb.dao.m2", mongoTemplateRef = "secondaryMongoTemplate")
public class MongoConfig2 {

    @Autowired
    private MultipleMongoProperties mongoDBConfigPro;

    @Bean("mongoDatabaseFactory2")
    public MongoDatabaseFactory mongo2(Environment environment,
                                       ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers,
                                       ObjectProvider<MongoClientSettings> settings) {
        MongoClient mongoClient = new MongoClientFactory(this.mongoDBConfigPro.getSecondary(), environment,
                builderCustomizers.orderedStream().collect(Collectors.toList()))
                .createMongoClient(settings.getIfAvailable());
        SimpleMongoClientDatabaseFactory simpleMongoClientDatabaseFactory = new SimpleMongoClientDatabaseFactory(mongoClient, mongoDBConfigPro.getPrimary().getDatabase());
        return simpleMongoClientDatabaseFactory;
    }

    @Bean
    @Qualifier("secondaryMongoTemplate")
    public MongoTemplate secondaryMongoTemplate(@Qualifier("mongoDatabaseFactory2") MongoDatabaseFactory mongoDatabaseFactory) throws Exception {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}
